<template>
	<view>
		<!-- :width="width" -->
		<!-- :fileList="list" -->
		<u-upload
			:height="height"
			:uploadText="uploadText"
			:maxCount="maxCount"
			:accept="accept"
			:multiple="multiple"
		  @afterRead="afterRead"
			@delete="deletePic"
		>
		</u-upload>
		
		<u-toast ref="uToast"></u-toast>
	</view>
</template>

<script>
	import {
	  baseUrl
	} from '@/common/config'
	
	export default {
		name:"uploadFile",
		props: {
			fileList: {
				type: Array,
				default: () => []
			},
		  width: { // 内部预览图片区域和选择图片按钮的区域宽度，单位rpx，不能是百分比，或者auto
		    type: Number,
		    default: 80
		  },
		  height: { // 内部预览图片区域和选择图片按钮的区域高度，单位rpx，不能是百分比，或者auto
		    type: Number,
		    default: 80
		  },
		  uploadText: { // 上传区域的提示文字
		    type: String,
		    default: ''
		  },
		  previewUrl: { // 预览图地址
		    type: Array
		  },
		  maxCount: { //上传个数限制
		    type: Number,
		    default: 1
		  },
			accept: {	// 上传类型，video 为 视频
				type: String,
				default: 'image'
			},
			maxSize: {	// 文件大小 size
				type: Number,
				default: 0
			},
		},
		data() {
			return {
				list: []
			};
		},
		watch: {
			fileList(val){
				this.list = []
				val.map(i => {
					this.list.push({url: i})
				})
			}
		},
		methods: {
		  // 删除图片
		  deletePic(event) {
		    this.list.splice(event.index, 1)
		    this.$emit('deleteFile', event.index) 
		  },
			// 新增图片
		  async afterRead(event) {
				// 判断文件类型
		    const fileType = event.file.url.split('.')[1]
				// 上传的文件为视频
		    if (fileType.toLowerCase() === 'mp4') {
					// 视频的时长
					const size = event.file.size / 1024 / 1024
					if(size > this.maxSize ){
						this.$refs.uToast.show({
						  message: `上传视频大小不能超过${this.maxSize}MB`,
						  type: 'error'
						})
						return
					}

		    } else {
					// 其他情况
				}
				
		    // 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
		    let lists = [].concat(event.file)
		    let fileListLen = this.list.length
				lists.map(item => {
					this.list.push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
		    for (let i = 0; i < lists.length; i++) {
		      const result = await this.uploadFilePromise(lists[i].url)
		      let item = this.list[fileListLen]
		      this.list.splice(fileListLen, 1, Object.assign(item, {
		        status: 'success',
		        message: '',
		        url: result
		      }))
		      fileListLen++
					// 返回地址
		      this.$emit('handleFile', result)
					// 返回地址 和 名字
		      this.$emit('handleFileInfo', {name: event.file.name, url: result})
		    }
		  },
		  uploadFilePromise(url) {
		    return new Promise((resolve, reject) => {
		      uni.uploadFile({
		        url: `${baseUrl}/user-center/app-file/upload-file`,
		        filePath: url,
		        name: 'file',
		        formData: {
		          user: 'test'
		        },
		        header: {
		          'Authorization': 'Bearer ' + uni.getStorageSync('access_token'),
		          "Content-Type": "multipart/form-data",
		        },
		        success: (res) => {
		          let result = JSON.parse(res.data)
		          resolve(result.datas)
		          this.$refs.uToast.show({
		            message: '操作成功',
		            type: 'default',
		          })
		        },
		        fail: () => {
		          this.$refs.uToast.show({
		            message: '操作失败',
		            type: 'error'
		          })
		        }
		      });
		    })
		  },
		
		}
	}
</script>

<style lang="scss">

</style>